package com.dems.task.job;

import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;

public class TokenUtil {
    public static String generateToken(String appId, String appSecret, String transId, String timestamp){
        StringBuilder sourceData = new StringBuilder();
        sourceData.append("app_id").append(appId).append("timestamp").append(timestamp)
                .append("trans_id").append(transId).append(appSecret);

        // 添加Bouncy Castle的安全提供者
        Security.addProvider(new BouncyCastleProvider());

        // 需要加密的数据
        String data = sourceData.toString();

        // 创建SM3 Digest实例
       return generateSM3(data);
    }

    public static String generateSM3(String data){
        Digest digest = new SM3Digest();

        // 初始化SM3计算
        digest.update(data.getBytes(), 0, data.getBytes().length);

        // 创建输出缓冲区
        byte[] hash = new byte[digest.getDigestSize()];

        // 计算SM3哈希值
        digest.doFinal(hash, 0);

        // 将哈希值转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        // 输出SM3加密后的结果
        System.out.println("SM3 Hash: " + hexString.toString());
        return hexString.toString();
    }

    /**
     * HMAC-MD5，Hash-based Message Authentication Code，是一种基于哈希函数和密钥的消息认证码算法，用于确保消息的完整性和认证。
     * <p>
     * 输入：待加密的字符串
     * 输出：与MD5一致
     * 应用：密码管理、数字签名、文件完整性校验
     * 安全性：★★☆☆☆
     *
     * @param plainString 明文
     * @param key         秘钥
     * @return cipherString 密文
     */
    public static String hmacMD5(String key, String plainString) {
        String cipherString = null;
        try {
            // 指定算法
            String algorithm = "HmacSHA256";
            // 创建密钥规范
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm);
            // 获取Mac对象实例
            Mac mac = Mac.getInstance(algorithm);
            // 初始化mac
            mac.init(secretKeySpec);
            // 计算mac
            byte[] macBytes = mac.doFinal(plainString.getBytes(StandardCharsets.UTF_8));
            // 输出为16进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : macBytes) {
                sb.append(String.format("%02x", b));
            }
            cipherString = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherString;
    }

}
